/**
 * 
 */

package com.chengyu.eyc.utils;

import java.util.Date;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.chengyu.eyc.constant.EycConstants;

import cn.hutool.core.codec.Base64;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
public final class JWTUtil {

    private static final String SUBJECT = "理车堂";

    public static String createJWT(String id) {
       return createJWT(id, SUBJECT, -1);
    }
    public static String createJWT(String id, String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject) // 主题
            .setIssuer(SUBJECT) // 签发者
            .setIssuedAt(now) // 签发时间
            .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }
    public static SecretKeySpec generalKey() {
        byte[] encodedKey = Base64.decode(EycConstants.JWT_SECERT);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    public static void main(String[] args) {
      String  token=createJWT("7546745774");
     log.info(token);
      Claims claims=parseJWT(token);
      log.info(claims.getId());
    }

    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }

    public static boolean validateJWT(String jwtStr) {
        try {
            parseJWT(jwtStr);
        } catch (ExpiredJwtException e) {
            log.error(e.getMessage(), e);
            return false;
        }
        return Boolean.TRUE;
    }
    private JWTUtil() {

    }

}
